package com.bdqn.t350.ch09.config.shiro;

import com.bdqn.t350.ch09.bean.User;
import com.bdqn.t350.ch09.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.List;


//@Configuration
public class MyShiroRealm extends AuthorizingRealm {
    @Resource
    UserService userService;

    /**
     * 认证
     *
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("进入自定义认证流程");
        //获取身份信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //根据token获取用户名，需要去数据库里面查找是否有该用户名
        String username = token.getUsername();
        User user = userService.selectByName(username);
        if (user == null) {
            throw new UnknownAccountException();
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                user,//身份(根据用户名去数据库查询出来的用户)
                user.getUsrPassword(),//密码，凭证
                getName());
        return info;
    }

    /**
     * 授权
     *
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入授权流程.....");
        //此时user里面应该要包含该用户能访问的资源
        User user = (User) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //给该用户授权能访问的资源
        //if(user.getUsrName().equals("czkt")){
        //info.addStringPermission("L05");
        //info.addStringPermission("L0503");
        //}
        List<String> list = userService.getByUserNameRightCode(user);
        for (String s : list) {
            info.addStringPermission(s);
        }
        return info;
    }


}
